package com.example.demo.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.example.demo.easyexcel.db.entity.BaseStudent;
import com.example.demo.easyexcel.db.entity.DemoData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjq
 * @version 创建时间：2021-12-17 15:05:13
 */

@Api(tags = {"学生信息模型，这里是将数据库数据的导出"})
@RestController
@RequestMapping("/baseStudent")
public class BaseStudentController {

    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     * @since 2.1.1
     */
    @ApiOperation(value = "web中的写并且失败的时候返回json")
    @GetMapping("downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        List<BaseStudent> list = new ArrayList<BaseStudent>();
        //这里可以插入一些默认数据


        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), BaseStudent.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @ApiOperation(value = "web中的写")
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {

        // 此方法可以写入excel，但导出的excel名称是乱码的
//		response.setContentType("application/vnd.ms-excel");
//		response.setCharacterEncoding("utf-8");
//		String fileName = URLEncoder.encode("测试", "UTF-8");
//		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//		EasyExcel.write(response.getOutputStream(), BaseStudent.class).sheet("模板").doWrite(list);

        // 使用postman进行测试，swagger会有问题
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("学生信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), BaseStudent.class).sheet("模板").doWrite(new ArrayList());
    }

}
